# coding: utf8

from enum import IntEnum
from collections import namedtuple
import random

# class MJCardColor(IntEnum):
#     kWan = 1
#     kTong = 2
#     kTiao = 3
#     kHua = 4

EMJCardColor = namedtuple("EMJCardColor", "kWan kTong kTiao kHua")(
    kWan = 1,
    kTong = 2,
    kTiao = 3,
    kHua = 4,
)

def get_card_color(card):
    return card >> 4

def get_card_value(card):
    return card & 0x0f

def gen_new_card():
    cards = []
    for color in EMJCardColor:
        #print(type(color), color)
        max_value = 9
        if color == EMJCardColor.kHua:
            max_value = 7
        for v in range(1, max_value + 1):
            for _ in range(0, 4):
                cards.append(color << 4 | v)
    return cards

RAW_CARDS = gen_new_card()


def dump_cards(cards:list[int]):
    print("dump_cards:")
    output_str = ""
    str_samples = []
    for card in cards:
        #print(f"c={get_card_color(card)},v={get_card_value(card)}")
        #output_str.join(format(card, "x"))
        str_samples.append(f"{hex(card)},")
        #str_samples.append(f"{card:x},")
    output_str = "".join(str_samples)
    print(output_str)

def gen_histogram(cards):
    higtogram_map = {}
    for card in cards:
        if card in higtogram_map:
            higtogram_map[card] += 1
        else:
            higtogram_map[card] = 1
    return higtogram_map

def gen_jiang_list(higtogram_map):
    jiang_list = []
    for k, v in higtogram_map.items():
        if v > 0:
            jiang_list.append(k)
    return jiang_list


def group_by_color(cards: list[int]):
    ''' 按花色分组 '''
    card_groups = {}
    for card in cards:
        card_groups.setdefault(get_card_color(card), []).append(cards)
    return card_groups

def check_3n(cards: list[int]):
    '''
    @brief 判定给定的牌是否构成3n结构
    加速逻辑：
    1.3n组合的值一定能被三整除
    '''
    if len(cards) == 0:
        return True
    #for card in cards:
    #    card


def check_hupai(cards: list[int]):
    ''''''
    #dump_cards(cards)
    cards = sorted(cards)
    #dump_cards(cards)
    histogram_map = gen_histogram(cards)
    jiang_list = gen_jiang_list(histogram_map)
    if jiang_list:
        #print(histogram_map)
        #print(jiang_list)
        card_groups = group_by_color(cards)
        return True
    return False

if __name__ == "__main__":
    #print(RAW_CARDS)
    #dump_cards(RAW_CARDS)
    while True:
        hand_card_cnt = 13 + 1 - 2
        hand_cards = random.sample(RAW_CARDS, hand_card_cnt)
        if check_hupai(hand_cards):
            break
